{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Chapter 2 - Syntax and Semantics with Scheme  \n",
    "## PPL 2020 http://www.cs.bgu.ac.il/~ppl202\n",
    "\n",
    "We have introduced the following main concepts in Chapter 1 through examples in JavaScript and TypeScript:\n",
    "\n",
    "* Different programming languages encourage different programming practices and make other practices difficult by providing programming tools and idioms.  We compared the familiar *procedural programming paradigm* with the *functional programming (FP) paradigm* and identified the key tools each provides (for FP: first-class citizen functions, immutability and functional abstractions).\n",
    "* We distinguished two aspects that participate in the definition of a programming language: the *syntax of expressions*, on the one hand, and the set of *values* that can be computed when evaluating the expressions in the language on the other. The process of mapping from expression to value is called *evaluation*.  The description of the evaluation algorithm for a given algorithm provides the *operational semantics* of the language.\n",
    "\n",
    "* Atomic vs. Compounds\n",
    "    * In the syntactic description of a language, we distinguished *atomic* expressions (which have no sub-components) and           *compound* expressions (which have sub-expressions).\n",
    "    * Similarly, in the semantic domain, we distinguish *atomic values* (such as boolean and numbers) \n",
    "      and *compound values* (such as arrays and maps)\n",
    "\n",
    "* *Data types* denote specific subsets of values over which operations can be performed uniformly.\n",
    "Programming languages define primitive data types (sets of values with well defined operations). \n",
    "They also provide means to define user defined types\n",
    "* A *type system* defines a *type language* to construct new data type expressions to *denote* useful sets of data structures.\n",
    "Relations of *subtyping* and *disjoint types* are derived from this perspective on types, and operations on types\n",
    "such as union, intersection and product provide ways to construct new types.  \n",
    "* A language with *type checking* allows programmers to annotate variables and functions with *type annotations* which express constraints on which values can be bound to these variables in any execution of the program.  The *type checker* can establish that a given program satisfies the type declaration constraints.  \n",
    "* The structure of type definitions is important in general because it provides an abstract\n",
    "model of the structure of the data values expected by functions, and the type of values they can return.  The structure of the code in the functions usually follows the structure of the data it receives.\n",
    "\n",
    "In Chapter 2, we develop these concepts in a more systematic and in-depth manner.  The method we use is to design a new programming language, to specify exactly its syntax and its operational semantics, and to implement this specification into an executable interpreter.  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Interpreters\n",
    "\n",
    "In this chapter, we define a small but complete programming language.  We demonstrate what are the elements necessary to define a programming language.  We first present these elements informally - to define a subset of the Scheme language.\n",
    "This language is a simple functional language.  \n",
    "\n",
    "We then move on to define the elements formally in the form of:\n",
    "* The syntax of the language (defining the set of expressions which belong to the language)\n",
    "* The operational semantics of the language (defining how to map any expression in the language to a value in a recursive manner).\n",
    "\n",
    "We implement these formal definitions into concrete programs - which together form an *interpreter* of the language."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As summarized by Hal Abelson in the introduction to *Essentials of Programming Languages* (Friedman, Wand and Haynes, 2000) - this chapter: \n",
    "*brings us face to face with the most fundamental idea in computer programming:\n",
    "The interpreter for a computer language is just another program.*\n",
    "\n",
    "Interpreters are interesting because:\n",
    "* They clarify *what programs do when they are executed*\n",
    "* They illustrate how to build a wide class of programs which transform complex data from one form into another based on syntactic structure.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Object Language vs. Meta Language\n",
    "\n",
    "We use interpreters to implement the formal definitions of a programming language.  \n",
    "The interpreter itself is written in a programming language, and it defines a programming language.\n",
    "To distinguish between these two programming roles, we use the following terminology:\n",
    "\n",
    "* The language we define and describe is called the *object language*\n",
    "* The language we use to implement the interpreter is called the *meta language*\n",
    "\n",
    "The choice of each of these languages (object and meta) depends on the objective we set for ourselves."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Scheme as an Object Language\n",
    "\n",
    "We introduce a subset of Scheme to illustrate how to specify a programming language and how to implement a full interpreter because Scheme is a *small language* (it has few primitives, few data types, an extremely simple and regular syntax)\n",
    "and a *simple language* (the evaluation rules are consistent and simple, there are not many special cases).\n",
    "Yet, Scheme is an *expressive* language - it is Turing complete, and because it follows the functional programming paradigm,\n",
    "it allows the definition of powerful functional abstractions which make programming productive.\n",
    "\n",
    "All of these elements stand in contrast with JavaScript - which has evolved into a *large language* with many primitives, a very complex syntax, and because it is a multi-paradigm language - supporting FP, OOP, procedural programming and more - JavaScript has a complex evaluation semantics.  \n",
    "\n",
    "We thus select to describe a *small and simple but full* language - a subset of Scheme - as the object language of this course."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## TypeScript as a Meta Language\n",
    "\n",
    "We select to use a subset of TypeScript used as a Functional Language to implement the interpreter.  \n",
    "One of the advantages of this decision is that we exploit the TypeScript type system to encode the objects manipulated in the interpreter - abstract syntax trees and values. If the algorithm of the operational semantics is well understood, it can be implemented as a pure functional model in a code that is surprisingly short and elegant - and ported to any functional language. \n",
    "\n",
    "Let us engage thus in developing a programming language bottom up, starting from small blocks and building up into a fuller version of a functional programming language."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Elements of a Programming Language\n",
    "\n",
    "How do we specify a programming language? What are the elements that together define a programming language?\n",
    "\n",
    "The key elements are:\n",
    "1. **Primitives**: expressions whose evaluation is built-in in the interpreter and which are not explained by the semantics of the language.  These include primitive operations (for example, arithmetic operations on number or comparison operators) and primitive literal values (for examples, numbers or boolean values).\n",
    "2. **Combination means**: ways to create compound expressions and compound values from simpler ones.\n",
    "3. **Abstraction means**: ways to manipulate compound objects (expressions or data values) as standalone units by giving them simple names.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The language definition is structured in two aspects:\n",
    "1. **Expressions** are the words and sentences of the language.\n",
    "2. **Values** are the results of the computation of expressions according to the evaluation rules of the language.  Values belong to the semantic domain of the language.\n",
    "\n",
    "To describe our object programming language, we first present all the types of expressions in the language (this is called the **syntax** of the language) on the one hand, and all the possible values that can be computed by the language on the other.\n",
    "The **syntax** is the input to the interpreter, the **values** are the output of the interpreter.\n",
    "\n",
    "We will introduce the syntax and semantics of the Scheme subset in several iterations - starting from the simplest forms \n",
    "of expressions, then describing the rules to evaluate their value, then introducing more complex forms of expressions and their evaluation rules."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Expressions\n",
    "\n",
    "We distinguish\n",
    "* **Atomic expressions**\n",
    "* **Compound expressions**\n",
    "\n",
    "### Atomic Expressions\n",
    "\n",
    "The following are the types of atomic expressions in Scheme:\n",
    "* **Literal numbers**: they are written as numbers such as `1`\n",
    "* **Literal booleans**: the true and false values are written `#t` and `#f`.  They are primitive literal atomic expressions.\n",
    "* **Primitive procedures**: are atomic expressions - they include arithmetic primitive operators `+`, `-`, `*`, `/` and comparison operators `<`, `>`, `=`.\n",
    "\n",
    "### Compound Expressions\n",
    "\n",
    "The only syntactic form used to combine expressions into complex expressions in Scheme is to arrange them into parentheses.\n",
    "\n",
    "```\n",
    "(+ 45 78) --> 123\n",
    "(- 56 9)  --> 47\n",
    "(* 6 50)  --> 300\n",
    "(/ 25 5)  --> 5\n",
    "```\n",
    "\n",
    "These expressions are called **forms**. \n",
    "Their structure is to always refer to the leftmost sub-expression of the form as an *operator* and the rest of the sub-expressions as *operands*.  Scheme compound expressions are always written in **prefix notation**.\n",
    "\n",
    "Forms can be nested recursively:\n",
    "\n",
    "```\n",
    "(+ (* 3 15) (-9 2)) --> 52\n",
    "```\n",
    "\n",
    "It helps to pretty print (or indent) such complex expressions to figure out their internal structure:\n",
    "\n",
    "```\n",
    "(+ (* 3\n",
    "      (+ 4 2)\n",
    "      (* 2 5))\n",
    "   7)\n",
    "```\n",
    "\n",
    "Expressions are evaluated by the interpreter and return a value.\n",
    "In Scheme, there are only expressions in the language.\n",
    "This is in contrast to JavaScript which contains expressions and **statements** (syntactic elements which, when evaluated, do not return a value, but simply execute a command)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Variables and Values\n",
    "\n",
    "The programming language provides means to **name objects**.  This is a fundamental form of **abstraction**: using a simple name instead of using a complex value or a complex expression.\n",
    "\n",
    "In Scheme, `define` is used to bind a name to the value of an expression.\n",
    "```\n",
    "(define size 6) \n",
    "\n",
    "(* 2 size) --> 12 ;; size is now understood \n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`size` in this context is called a **variable**.\n",
    "The relation between a variable and the value it denotes is called a **binding**.\n",
    "\n",
    "Variables can be used as atomic expressions.\n",
    "They are evaluated to the value to which they were bound using `define`.\n",
    "\n",
    "`define` is a form of *abstraction* because it allows the programmer to use names (variables) instead of complex operations.\n",
    "\n",
    "```\n",
    "(define area (* size size)) --> 36\n",
    "```\n",
    "\n",
    "In the syntax of a `define` operation, `define` is a **special operator** - it indicates that a special operation must be performed by the interpreter to evaluate the `(define <var> <expression>)` form.  \n",
    "\n",
    "The result of evaluating a `define` form is that the interpreter remembers that the variable is now bound to a value.\n",
    "The steps of this evaluation are:\n",
    "\n",
    "```\n",
    "Evaluation rule for forms of the type: (define <var> <exp>)\n",
    "1. Let val = Evaluate(<exp>)\n",
    "2. Add the binding < <var>, val > to the global environment\n",
    "```\n",
    "\n",
    "The global environment is a function which maps variable names to values.  \n",
    "It is best to think of it as an object of type `variable => value`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Expression Types and Evaluation Rules - Round 1\n",
    "\n",
    "We have now presented different expression types with the corresponding evaluation rules for each type of expression.\n",
    "Let us call this language $L1$ and summarize the rules to evaluate all of the expression types in $L1$.  \n",
    "We also summarize the set of all possible values computed by $L1$.\n",
    "\n",
    "### Expression Types\n",
    "\n",
    "All the expression types presented so far are:\n",
    "1. Atomic expressions:\n",
    "   1. number literal expression (0, 1, 2, ...)\n",
    "   2. boolean literal expression (#t and #f)\n",
    "   3. primitive operation expression (+, -, *, /, <, >, =)\n",
    "   4. variable expression (a well formed name - made up of letters and punctuations)\n",
    "2. Compound expressions:\n",
    "   1. Special compound expressions: `(define <var> <exp>)` - where `<var>` is a variable expression and `<exp>` is any expression except a define expression.\n",
    "   2. Non-special compound expressions: $(exp_0 \\ldots exp_n)$ - where each $exp_i$ is any expression type except a define expression.\n",
    "   \n",
    "This inductive definition corresponds to the set $Expression$ of all possible expressions in the language. (The definition is *inductive* because we use the term\n",
    "*expression* to define what are compound expressions.)\n",
    "\n",
    "### Evaluation Rules for Expressions\n",
    "\n",
    "We define the function $evaluate: Expression \\rightarrow Value$ in an inductive manner:\n",
    "\n",
    "#### 1. Evaluation of atomic expressions:\n",
    "1. Variables are evaluated by looking up their value in the global environment.\n",
    "2. Primitive atomic expressions evaluate to their pre-defined denoted value.\n",
    "   * Number atomic literal expressions evaluate to number values.\n",
    "   * Boolean atomic literal expressions evaluate to boolean values true and false.\n",
    "   * Primitive procedures evaluate to the primitive function that performs the denoted operation.\n",
    "   \n",
    "#### 2. Evaluation of compound special forms:\n",
    "1. For each special form - a special evaluation rule exists.\n",
    "   * The special form `(define <var> <exp>)` is evaluated according to this rule:\n",
    "     1. Let val = `evaluate(<exp>)`\n",
    "     2. Add the binding `< <var>, val >` to the global environment.\n",
    "     3. The form returns a special `void` value.\n",
    "\n",
    "Note that in this rule, the sub-expression `<var>` is **not** evaluated.\n",
    "\n",
    "We have only introduced one special form `define` so far - we will introduce more later.\n",
    "\n",
    "#### 3. Evaluation of compound non-special forms:\n",
    "All compound forms are of the form $(exp_0 \\ldots exp_n)$.\n",
    "1. Let $(val_0 \\ldots val_n) = (evaluate(exp_0) \\ldots evaluate(exp_n))$\n",
    "2. Apply the procedure $val_0$ to the values $(val_1 \\ldots val_n)$.\n",
    "\n",
    "**NOTE**: We assume that $val_0$ evaluates into a primitive procedure - otherwise the second step above will not succeed.\n",
    "Can you think of which expressions are evaluated into primitive procedure values?\n",
    "\n",
    "**NOTE**: Observe that this definition of the `evaluate` function is inductive - and that it follows the inductive definition of the set of expressions.\n",
    "\n",
    "### Computed Values\n",
    "\n",
    "Looking at all the evaluation rules, we can summarize the set of all possible values that can be returned by an invocation\n",
    "of evaluate:\n",
    "* Number values\n",
    "* Boolean values\n",
    "* Primitive operations (the value of primitive operators like `+` or `<`).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example Programs in $L1$\n",
    "\n",
    "Let us write a few examples of programs in $L1$:\n",
    "\n",
    "```\n",
    "5 --> 5\n",
    "\n",
    "(* 3 2) --> 6\n",
    "\n",
    "(+ (* 3 2) 4) --> 10\n",
    "\n",
    "(> 2 3) --> #f\n",
    "\n",
    "(= 2 (+ 1 1)) --> #t\n",
    "```\n",
    "\n",
    "Note that expressions in general are evaluated one by one.\n",
    "The order in which expressions are evaluated does not change their value.\n",
    "\n",
    "Only in the case of the `define` form, there is a side-effect which makes the sequence of expressions significant:  \n",
    "\n",
    "```\n",
    "(define radius 12)\n",
    "(define pi 3.14)\n",
    "(define area (* (* radius radius) pi))\n",
    "\n",
    "(+ area (* 2 3))\n",
    "```\n",
    "\n",
    "#### Sequences in $L1$\n",
    "\n",
    "In order to make sense of a program that includes `define` forms, we must define a compound expression which is a sequence of expressions and its evaluation rule.  We will describe the details of the evaluation rule for sequences including define-expressions in more details later."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### What is Not in $L1$\n",
    "\n",
    "Let us try to assess what programs can be written in $L1$ as defined.\n",
    "\n",
    "On the side of the restrictions - we have:\n",
    "* Few primitives - and no way to define other functions besides primitive functions (no *functional abstraction means*).\n",
    "* The computed values can only be numbers or booleans - there are no way to build compound values (no *value composition means*).\n",
    "* We can define global variables and no scoping mechanism\n",
    "* There are no control structures: no conditionals, no loops (sequence and embedding are the only *control composition means*)\n",
    "\n",
    "On the positive side:\n",
    "* We can build expressions as deeply nested as required\n",
    "* We can give names to complex expressions so that they can be reused to avoid repetition\n",
    "\n",
    "**NOTE**:  consider the claim that **programs in $L1$ always terminate**.  Can you prove it? (Using structural induction)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## $L2$: User Defined Procedures and Conditional Expressions\n",
    "\n",
    "Let us introduce two new types of expression into $L1$ - leading to a new language we will call $L2$.\n",
    "We choose to add together user defined procedures and conditional expressions - because these two language\n",
    "facilities *work well together*.  The reason is that we will develop recursive functions - and when we write\n",
    "a recursive function, it helps to be able to test for the base case vs. recursive case.\n",
    "\n",
    "\n",
    "### Compound Procedure Definition with Lambda\n",
    "\n",
    "`lambda` is a special operator which can be used in a special form of type `lambda`.\n",
    "The syntax is:\n",
    "```\n",
    "(lambda (<var> ...) <exp> ...)\n",
    "```\n",
    "\n",
    "For example:\n",
    "```\n",
    "(lambda (x) (* x x))\n",
    "```\n",
    "This expression is a procedure expression.  It has three sub-expressions:\n",
    "* The special operator `lambda`\n",
    "* The list of parameters - all of which are variables.\n",
    "* The body of the procedure - which is an expression.\n",
    "\n",
    "When this expression is evaluated, it creates a value whose type is called a **closure**.\n",
    "We will denote such values as `<Closure (x) (* x x)>`.\n",
    "\n",
    "**NOTE**: `(lambda (x) (* x x))` is an expression.  `<Closure (x) (* x x)>` is a value.\n",
    "This is a similar distinction as: the literal expression `2` is an expression.  Its value is the number 2.\n",
    "\n",
    "**NOTE**: The expression `(lambda (x) (* x x))` in Scheme is equivalent to `(x) => x * x` in TypeScript.\n",
    "The difference is syntactic only:\n",
    "* Scheme prefers prefix notation (which is the general syntactic preference of Scheme for all syntactic constructs).\n",
    "* The only delimiters in Scheme are parentheses - whereas in TypeScript there is a selection of {} and punctuation (=>);\n",
    "* In Scheme every syntactic construct is an expression - in contrast in JavaScript there can be expressions or statements.\n",
    "When statements are used, the special form `return` must be used - when they are not, it can be skipped.  In general,\n",
    "Scheme's syntax is more consistent - but it can be less readable to the untrained eye.\n",
    "\n",
    "\n",
    "#### Closures: Composite or Atomic Values?\n",
    "\n",
    "A closure value contains multiple parts - the parameters and the body.\n",
    "But there are no accessors to take apart these components from the value.\n",
    "\n",
    "This leads to an interesting distinction:\n",
    "* From the programmer perspective, a closure is an atomic value.\n",
    "* From the interpreter perspective, a closure is a compound data structure with accessible sub-components.\n",
    "\n",
    "When a `lambda` expression is evaluated, the `body` is **not** evaluated.\n",
    "\n",
    "#### Naming User Procedures\n",
    "\n",
    "To give a name to a procedure, we use the existing `define` mechanism:\n",
    "\n",
    "```\n",
    "(define square (lambda (x) (* x x)))\n",
    "```\n",
    "\n",
    "We will see later in the course that the capability to name procedures is *a big deal* - as it allows the definition\n",
    "of recursive functions - and, in particular, it changes the expressive power of the programming language."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Compound Procedure Application\n",
    "\n",
    "When a `lambda` expression is computed, we obtain a closure.  Closures can then be applied to values.\n",
    "This is the mechanism used when applying a closure to values:\n",
    "\n",
    "Recall the evaluation rule for non-special forms in $L1$:\n",
    "\n",
    "Given a compound forms of the form $(exp_0 \\ldots exp_n)$ where $exp_0$ is not a special operator:\n",
    "1. Let $(val_0 \\ldots val_n) = (evaluate(exp_0) \\ldots evaluate(exp_n))$\n",
    "2. Apply the procedure $val_0$ to the values $(val_1 \\ldots val_n)$.\n",
    "\n",
    "In $L1$ - the only possible procedure values were primitive procedures (the value of the atomic expressions `+`, `*` etc).\n",
    "\n",
    "In $L2$ - we also have user created closures.\n",
    "\n",
    "The way a closure $val_0$ = `<Closure <p1, ..., pn> <exp1> ... <expk>>` is applied to values $(val_1, \\ldots, val_n)$ is according to the following rule:\n",
    "1. Replace all occurrences of $p_1, \\ldots, p_n$ in the expressions `<exp1> ... <expk>` of the body of the procedure with the corresponding values $val_1, \\ldots, val_n$.\n",
    "2. Evaluate all resulting expressions.\n",
    "3. The value returned by the application is the value of the last expression `<expk>`.\n",
    "\n",
    "In summary:\n",
    "* We introduced a new syntactic form (lambda expressions) and a new type of values (closures).\n",
    "* We defined the evaluation rule for lambda expressions - which yield closures - without performing any recursive evaluation.\n",
    "* Finally, we expanded the evaluation rule of non-special forms to work for the case where the operator value is a closure type - in addition to the known case in $L1$ where the operator value was a primitive operator.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conditional Expressions\n",
    "\n",
    "We introduce a third special form to the syntax of the language, in addition to `define` and `lambda` together with its specific evaluation rule to enable conditional evaluation.\n",
    "\n",
    "The syntax of a Scheme conditional expression is:\n",
    "\n",
    "```\n",
    "(if <exp> <exp> <exp>)\n",
    "```\n",
    "\n",
    "For example:\n",
    "\n",
    "```\n",
    "(if (> x 2) x (* x 2))\n",
    "```\n",
    "\n",
    "`if` is a special operator - it has a special evaluation rule.\n",
    "The three other sub-expressions are called the test-part, then-part, and else-part of the compound if-expression.\n",
    "They can recursively be any type of expression.\n",
    "\n",
    "**NOTE**: if-expressions are *expressions* - not *statements* as they are in TypeScript.  They are evaluated into a value.\n",
    "They are equivalent to the ternary `?:` operator we used in TypeScript.\n",
    "\n",
    "#### Example: abs\n",
    "\n",
    "```\n",
    "(define abs (lambda (x) (if (> x 0) x (- x))))\n",
    "\n",
    "(abs 2)  --> 2\n",
    "(abs -3) --> 3\n",
    "```\n",
    "\n",
    "if-expressions can be nested as needed to define complicated decisions:\n",
    "\n",
    "```\n",
    "(if (= x y)\n",
    "    0\n",
    "    (if (> x y)\n",
    "        1\n",
    "        -1))\n",
    "```\n",
    "\n",
    "Scheme also includes an additional special form called `cond` which allows a more general form of conditional expression:\n",
    "\n",
    "```\n",
    "(cond (<p1> <e11> <e12> ... <e1k1>)\n",
    "      (<p2> <e21> <e22> ... <e2k2}>)\n",
    "      ...\n",
    "      (else <en1> <en2> ... <enkn}>))\n",
    "```\n",
    "\n",
    "The sub-expressions of the `cond` form are called *clauses* - each clause starts with a predicate-expression and is followed by consequence-expressions.\n",
    "\n",
    "### Evaluation Rule for If-expressions\n",
    "\n",
    "To evaluate an if-expression `(if <test-exp> <then-exp> <else-exp>)`:\n",
    "1. Let p = `evaluate <test-exp>`\n",
    "2. If p is true, then evaluate `<then-exp>` and return this value as the value of the if-expression.\n",
    "2. else evaluate `<else-exp>` and return its value as the value of the if-expression.\n",
    "\n",
    "**NOTE**: When evaluating an if-expression, the `<test-exp>` is always evaluated, but only one of `<then-exp>` or `<else-exp>` \n",
    "is evaluated.  This is in contrast to what happens when we evaluate a non-special form - where all the sub-expressions are always evaluated."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example Program in $L2$\n",
    "\n",
    "The language we have defined so far is quite expressive.  Let us define an example program demonsrating this:\n",
    "this program implements Newton's method for computing square roots.\n",
    "\n",
    "Newton's method is stated as this algorithm:\n",
    "* If y is non-zero guess for a square root of x, then $(y + x/y)/2$ is a better approximation of $\\sqrt x$.\n",
    "\n",
    "To start this computation, we provide a non-zero guess like 1, and we need to decide when to stop guessing.\n",
    "\n",
    "This algorithm is iterative:\n",
    "* Is the current guess good enough? if yes return it.\n",
    "* Else improve the guess and try again.\n",
    "\n",
    "Interestingly - we can implement this iterative algorithm even though we have no construct in the language to iterate."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "(define sqrt (lambda (x) (sqrt-iter 1 x)))\n",
    "\n",
    "(define sqrt-iter\n",
    "  (lambda (guess x)\n",
    "     (if (good-enough? guess x)\n",
    "         guess\n",
    "         (sqrt-iter (improve guess x)\n",
    "                    x))))\n",
    "\n",
    "(define abs (lambda (x) (if (< x 0) (- x) x)))\n",
    "(define square (lambda (x) (* x x)))\n",
    "(define epsilon 0.0001)\n",
    "\n",
    "(define good-enough?\n",
    "  (lambda (guess x)\n",
    "     (< (abs (- (square guess) x) eps)))\n",
    " \n",
    "(define average\n",
    "  (lambda (x y) (/ (+ x y) 2)))\n",
    "  \n",
    "(define improve\n",
    "  (lambda (guess x)\n",
    "    (average guess (/ x guess))))\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This program illustrates many of the \"good properties\" we associated with the Procedural Programming paradigm in Chapter 1:\n",
    "* Encourage the use of small units of codes, called procedures, which encapsulate well-defined commands. \n",
    "* Procedures interact through well-defined interfaces published by each procedure (the contract of the procedure, including the signature of which arguments it expects, and which return value it returns)\n",
    "\n",
    "We haven't discussed local variables (used inside each procedure without affecting the state of the program outside the scope of the procedures).  We will see later in the chapter that even in $L2$, we have enough *semantic power* to define local variables, but we have not provided *syntactic constructs* to encourage the use of this feature.\n",
    "\n",
    "We have created a hierarchy of procedures, higher-level procedures call lower-level procedures:\n",
    "\n",
    "```\n",
    "sqrt --> sqrt-iter --> good-enough --> square, abs\n",
    "                       improve --> average \n",
    "```                   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Expression Types and Evaluation Rules - Round 2\n",
    "\n",
    "Let us summarize the syntax (expression types) of the language $L2$ and summarize the rules to evaluate all of the expression types in $L2$.  \n",
    "\n",
    "### Expression Types\n",
    "\n",
    "All the expression types presented so far are:\n",
    "1. Atomic expressions:\n",
    "   1. number literal expression (0, 1, 2, ...)\n",
    "   2. boolean literal expression (#t and #f)\n",
    "   3. primitive operation expression (+, -, *, /, <, >, =)\n",
    "   4. variable expression (a well formed name - made up of letters and punctuations)\n",
    "2. Compound expressions:\n",
    "   1. Special compound expressions: \n",
    "      * `(define <var> <exp>)`\n",
    "      * `(lambda (<var> ...) <exp> ...)`\n",
    "      * `(if <exp> <exp> <exp>)`\n",
    "      * `(cond (<exp> ...) ...)`\n",
    "   2. Non-special compound expressions: $(exp_0 \\ldots exp_n)$\n",
    "   \n",
    "This inductive definition corresponds to the set $Expression$ of all possible expressions in the language.\n",
    "\n",
    "### Evaluation Rules for Expressions\n",
    "\n",
    "We define the function $evaluate: Expression \\rightarrow Value$ in an inductive manner:\n",
    "\n",
    "#### 1. Evaluation of atomic expressions:\n",
    "1. Special operators are not evaluated (`define`, `lambda`, `if`, `cond` and `else` are the special operators).\n",
    "2. Variables are evaluated by looking up their value in the global environment.\n",
    "3. Primitive atomic expressions evaluate to their pre-defined denoted value.\n",
    "   * Number atomic literal expressions evaluate to number values.\n",
    "   * Boolean atomic literal expressions evaluate to boolean values true and false.\n",
    "   * Primitive procedures evaluate to the primitive function that performs the denoted operation.\n",
    "   \n",
    "#### 2. Evaluation of compound special forms:\n",
    "1. The special form `(define <var> <exp>)` is evaluated according to this rule:\n",
    "     1. Let val = `evaluate(<exp>)`\n",
    "     2. Add the binding `< <var>, val >` to the global environment.\n",
    "     3. The form does not have any value (which we state as it has a `void` value).\n",
    "2. The special form `(lambda (<p1> ..) <exp1> ...)` is evaluated into a value `<Closure (<p1>...) <exp1>...>`.\n",
    "     Note that the sub-expressions of the lambda-form are not evaluated.\n",
    "3. The special form `(if <test-exp> <then-exp> <else-exp>)` is evaluated as follows:\n",
    "     * Let p = evaluate(`<test-exp>`)\n",
    "     * If p is true - the value of the if-expression is evaluate(`<then-exp>`)\n",
    "     * else it is evaluate(`<else-exp>`).\n",
    "  \n",
    "A similar rule applies for `cond`. For all special forms - not all sub-expressions are evaluated.\n",
    "\n",
    "\n",
    "#### 3. Evaluation of compound non-special forms:\n",
    "All compound forms are of the form $(exp_0 \\ldots exp_n)$.\n",
    "1. Let $(val_0, \\ldots, val_n) = (evaluate(exp_0), \\ldots, evaluate(exp_n))$\n",
    "2. If $val_0$ is a primitive procedure: Apply the procedure $val_0$ to the values $(val_1, \\ldots, val_n)$.\n",
    "3. Else if $val_0$ is a closure `<Closure <p1...pn> <exp1>..<expk>)`:\n",
    "   * Replace $p_1 ... p_n$ by $val_1 ... val_n$ in `<exp1> .. <expk>`\n",
    "   * Evaluate the resulting expressions and return the value of `<expk>`.\n",
    "\n",
    "**MISSING PARTS**: In this specification, we did not explain yet:\n",
    "* how the substitution operation works in step 3.\n",
    "* how to behave for error cases (wrong number of arguments, wrong type of value for $val_0$).\n",
    "* how the global environment works (to extend the environment when `define` is invoked and to apply the environment when a variable is evaluated).\n",
    "\n",
    "These parts will become explicit and will need to be specified when we implement the evaluation rules in the code of the interpreter.\n",
    "\n",
    "### Computed Values\n",
    "\n",
    "The set of all possible values computed by $L2$ is:\n",
    "* Numbers\n",
    "* Booleans\n",
    "* Primitive operations\n",
    "* Closures\n",
    "\n",
    "### What is Not in $L2$\n",
    "\n",
    "Note the programming constructs which are absent from $L2$:\n",
    "* No loop data sructures.\n",
    "* No mutation of variables.\n",
    "* No compound data structures.\n",
    "* No local variables.\n",
    "\n",
    "### Termination\n",
    "\n",
    "Can you prove that some programs in $L2$ may not terminate?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Extending the Language with Compound Values: $L3$\n",
    "\n",
    "We observe that the computed values of $L2$ are atomic values (numbers, booleans) or closures (which are a compoound value but which has no accessors).\n",
    "\n",
    "To introduce compound data values in the language, we need:\n",
    "* Constructors for compound values\n",
    "* Literal expressions that denote compound values\n",
    "\n",
    "In JavaScript, for example, compound values are constructed with the array and map constructors and denoted by the [] and {} notations for literal expressions.\n",
    "\n",
    "In the minimalistic spirit which characterizes Scheme, we will introduce into $L3$ a single compound value constructor and the capability to use it recursively."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The Pair Compound Data Type\n",
    "\n",
    "A pair is a minimal compound data type that combines two values together into a single new unit.\n",
    "The language supports this by introducing:\n",
    "* A value constructor: this is called `cons` in Scheme \n",
    "* Accessors to take apart a compound pair value: these are called `car` and `cdr` (for the first and second element of the pair).\n",
    "* A type predicate to check whether a value belongs to the set of pair values: `pair?`.\n",
    "* An equality predicate for pairs `equal?`.\n",
    "\n",
    "We thus extend the language with 5 primitive functions: `cons`, `car`, `cdr`, `pair?`, `equal?`.\n",
    "\n",
    "In addition, Scheme defines a standard form to print pair values and literal expressions that denote pair values:\n",
    "A literal pair expression is denoted as `'( <exp> . <exp> )`.  For example:\n",
    "\n",
    "```\n",
    "(define p1 '(1 . 5))    ;; literal pair expression \n",
    "(define p2 (cons 1 5))  ;; constructor invocation\n",
    "\n",
    "(car p1) --> 1\n",
    "(cdr p1) --> 5\n",
    "```\n",
    "\n",
    "Pairs can be combined recursively into complex compound values:\n",
    "```\n",
    "(define p3 (cons p1 p2))\n",
    "(define p4 (cons p3 p2))\n",
    "\n",
    "(car p3) --> '(1 . 5)\n",
    "(cdr p3) --> '(1 . 5)\n",
    "```\n",
    "\n",
    "**NOTE**: The `cons` Pair constructor can receive parameters of any types.\n",
    "The type of `cons` is thus described as `(first T1, second T2)=>Pair(T1,T2)`.\n",
    "\n",
    "```\n",
    "(cons #t 1) --> '(#t . 1)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The List Compound Data Type\n",
    "\n",
    "\n",
    "In addition to the Pair data type, $L3$ introduces a recursive data type - called List.\n",
    "We first introduce it inductively:\n",
    "* The *empty list* denoted '() is the base case.\n",
    "* A non empty list is built by combining a value $v_0$ together with a list $(v_1, \\ldots, v_n)$ to obtain a non empty list $(v_0 v_1 \\ldots v_n)$ - which combines a *head* ($v_0$) and a *tail* which is a list.\n",
    "\n",
    "Non empty lists are constructed from a value and a list. The size that characterizes lists in this inductive definition is the length of the list: a list of size $n+1$ is constructed from a value and a list of size $n$.\n",
    "\n",
    "The definition of this inductive data type is a **disjoint union** between the empty list and non-empty lists.\n",
    "\n",
    "Scheme implements List values by re-using the Pair data type for non-empty lists and a special value for the empty list.\n",
    "The additions to the language are:\n",
    "* A new primitive value '() and a corresponding predicate `empty?`\n",
    "* A special type of literal compound expressions for list values: `'(e1 ... en)` (This is read `\"quote e1 ... en\"`)\n",
    "* The predicate primitive `list?` to check that an object belongs to the `List` data type (either empty or non empty).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "(define l14 (cons 1 (cons 2 (cons 3 (cons 4 '()))))) --> '(1 2 3 4)\n",
    "(list? l12) --> #t\n",
    "(cdr l14)   --> '(2 3 4)\n",
    "(car (cdr l14)) --> 2\n",
    "(cons 10 l14)   --> '(10 1 2 3 4)\n",
    "```\n",
    "\n",
    "On the basis of this inductive definition, we can define functions over lists:\n",
    "\n",
    "```\n",
    "(define length\n",
    "  (lambda (l)\n",
    "    (if (empty? l)\n",
    "        0\n",
    "        (+ 1 (length (cdr l))))))\n",
    "```\n",
    "\n",
    "As usual, recursive functions operating over an inductive type have a structure similar to the inductive definition of the inductive compound data type: because List is a disjoint union over Empty and Non-Empty lists, the structure of a function operating over lists will be:\n",
    "```\n",
    "    (if (empty? l)\n",
    "        <process empty list case>\n",
    "        <process non-empty list case>\n",
    "```\n",
    "For example:\n",
    "```\n",
    "(define nth\n",
    "  (lambda (n l)\n",
    "    (if (empty? l)\n",
    "        '()\n",
    "        (if (= n 0)\n",
    "            (car l)\n",
    "            (nth (- n 1) (cdr l))))))\n",
    "            \n",
    "(nth 2 '(0 1 2 3 4)) --> 2\n",
    "(nth 3 '(0 1))       --> '()\n",
    "```\n",
    "\n",
    "The list constructor can also receive parameters of any types.  In particular, we can create list of pairs and \n",
    "recursive tree structures using the compound list data type.\n",
    "\n",
    "Another list constructor is available in Scheme - which avoids the need for nested calls to `cons`: \n",
    "`(list <e1> ... <en>) --> '(v1 ... vn)` where `vi` is the value of `<ei>`.  \n",
    "Syntactically, `list` is complex because it can take variable number of arguments. \n",
    "\n",
    "**NOTE**: Compare `(list 1 2)` and `(cons 1 2)` - how different are they?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Expression Types and Evaluation Rules - Round 3\n",
    "\n",
    "Let us summarize the syntax (expression types) of the language $L3$ and the rules to evaluate all of the expression types in $L3$.  \n",
    "\n",
    "### Expression Types\n",
    "\n",
    "All the expression types presented so far are:\n",
    "1. Atomic expressions:\n",
    "   1. number literal expression (`0, 1, 2`, ...)\n",
    "   2. boolean literal expression (`#t` and `#f`)\n",
    "   3. primitive operation expression (+, -, \\*, /, <, >, =, **cons, car, cdr, pair?, list?** )\n",
    "   4. variable expression (a well formed name - made up letters and punctuations)\n",
    "   5. **the empty list literal expression '()**\n",
    "2. Compound expressions:\n",
    "   1. **Literal compound expressions: denoted `'(<lit> . <lit>)` for pairs or `'(<lit> ... <lit>)` for lists.** where `<lit>` \n",
    "      is an embedded literal expression (either atomic or compound).\n",
    "   2. Special compound expressions: \n",
    "      * `(define <var> <exp>)`\n",
    "      * `(lambda (<var> ...) <exp> ...)`\n",
    "      * `(if <exp> <exp> <exp>)`\n",
    "      * `(cond (<exp> ...) ...)`\n",
    "   3. Non-special compound expressions: $(exp_0 \\ldots exp_n)$\n",
    "   \n",
    "This inductive definition corresponds to the set $Expression$ of all possible expressions in the language.\n",
    "\n",
    "### Evaluation Rules for Expressions\n",
    "\n",
    "We define the function $evaluate: Expression \\rightarrow Value$ in an inductive manner:\n",
    "\n",
    "#### 1. Evaluation of atomic expressions:\n",
    "1. Special operators are not evaluated (`define`, `lambda`, `if`, `cond` and `else` are the special operators).\n",
    "2. Variables are evaluated by looking up their value in the global environment.\n",
    "3. Primitive atomic expressions evaluate to their pre-defined denoted value.\n",
    "   * Number atomic literal expressions evaluate to number values.\n",
    "   * Boolean atomic literal expressions evaluate to boolean values true and false.\n",
    "   * Primitive procedures evaluate to the primitive function that performs the denoted operation.\n",
    "   * **The Empty list atomic literal expression evaluates to an empty list value.**\n",
    "   \n",
    "#### 2. Evaluation of compound special forms:\n",
    "1. The special form `(define <var> <exp>)` is evaluated according to this rule:\n",
    "     1. Let val = `evaluate(<exp>)`\n",
    "     2. Add the binding `< <var>, val >` to the global environment.\n",
    "     3. The form does not have any value (which we state as: it has a `void` value).\n",
    "     4. **Compound literal expressions evaluate to compound values (pair or list).** \n",
    "2. The special form `(lambda (<p1> ..) <exp1> ...)` is evaluated into a value `<Closure (<p1>...) <exp1>...>`.\n",
    "     Note that the sub-expressions of the lambda-form are not evaluated.\n",
    "3. The special form `(if <test-exp> <then-exp> <else-exp>)` is evaluated as follows:\n",
    "    1. Let p = evaluate(`<test-exp>`)\n",
    "    2. If p is true - the value of the if-expression is evaluate(`<then-exp>`)\n",
    "    3. else it is evaluate(`<else-exp>`).\n",
    "  \n",
    "A similar rule applies for `cond`. For all special forms - not all sub-expressions are evaluated.\n",
    "\n",
    "\n",
    "#### 3. Evaluation of compound non-special forms:\n",
    "All compound forms are of the form $(exp_0, \\ldots, exp_n)$.\n",
    "1. Let $(val_0, \\ldots, val_n) = (evaluate(exp_0), \\ldots, evaluate(exp_n))$\n",
    "2. If $val_0$ is a primitive procedure: Apply the procedure $val_0$ to the values $(val_1, \\ldots, val_n)$.\n",
    "3. Else if $val_0$ is a closure `<Closure <p1...pn> <exp1>..<expk>)`:\n",
    "   * Replace $p_1 ... p_n$ by $val_1 ... val_n$ in `<exp1> .. <expk>`\n",
    "   * Evaluate the resulting expressions and return the value of `<expk>`.\n",
    "\n",
    "### Computed Values\n",
    "\n",
    "The set of all possible values computed by $L3$ is:\n",
    "* Numbers\n",
    "* Booleans\n",
    "* Primitive operations\n",
    "* Closures\n",
    "* **Pairs**\n",
    "* **Lists** (empty or non-empty lists).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Comparison Functional JavaScript and $L3$\n",
    "\n",
    "Let us compare the language we have obtained in $L3$ and the Functional JavaScript subset we used in Chapter 1:\n",
    "* $L3$ does not have local variables - JavaScript can define them with `let`.\n",
    "* $L3$ has less primitive operations, less primitive data types (no strings), less compound data types (no maps - arrays are quite similar to Scheme lists).\n",
    "* There is no mutation in $L3$ of variables and of compound data values (in contrast to JavaScript)."
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}